package com.tul.vapp.servicecenter.service.impl;

import com.tul.cusa.zookeeper.IZookeeperClient;
import com.tul.vapp.servicecenter.service.IZkService;
import com.tul.vapp.servicecenter.zookeeper.ZooKeeperClientFactory;
import org.springframework.stereotype.Service;

import java.nio.charset.Charset;
import java.util.List;

/**
 * 提供操作ZK的API
 *
 * @author wwxiang
 * @since 2017/12/29.
 */
@Service
public class ZkService implements IZkService {

    private static final Charset UTF8 = Charset.forName("UTF-8");

    private static final String ROOT_CONFIG = "/config";

    private static final String SEPARATOR = "/";

    private IZookeeperClient client;

    /**
     * 初始化ZkService
     */
    public ZkService() {
        this.client = ZooKeeperClientFactory.getClient();
        if (!client.exists(ROOT_CONFIG)) {
            client.create(ROOT_CONFIG, false);
        }
    }

    @Override
    public boolean createApp(String appId) {
        String path = ROOT_CONFIG + SEPARATOR + appId;
        if (!client.exists(path)) {
            client.create(path, false);
        }
        return true;
    }

    @Override
    public boolean createNamespace(String appId, String namespace, String content) {
        // 调用此方法前,请确保config/appId节点一定存在
        String path = ROOT_CONFIG + SEPARATOR + appId + SEPARATOR + namespace;
        if (!client.exists(path)) {
            client.create(path, false, content.getBytes());
        }
        return true;
    }

    @Override
    public boolean notifyZk(String appId, String namespace, String content) {
        String path = ROOT_CONFIG + SEPARATOR + appId + SEPARATOR + namespace;
        client.setData(path, content.getBytes(UTF8));
        return true;
    }

    @Override
    public boolean deleteApp(String appId) {
        String path = ROOT_CONFIG + SEPARATOR + appId;
        client.delete(path);
        return true;
    }

    @Override
    public boolean deleteNamespace(String appId, String namespace) {
        String path = ROOT_CONFIG + SEPARATOR + appId + SEPARATOR + namespace;
        client.delete(path);
        return true;
    }

    @Override
    public List<String> getApps() {
        String path = ROOT_CONFIG;
        return client.getChildren(path);
    }

    @Override
    public List<String> getNamespace(String appId) {
        String path = ROOT_CONFIG + SEPARATOR + appId;
        return client.getChildren(path);
    }

    @Override
    public String getItems(String appId, String namespace) {
        String path = ROOT_CONFIG + SEPARATOR + appId + SEPARATOR + namespace;
        byte[] content = client.getData(path);
        String result = new String(content, UTF8);
        return result;
    }
}
